package com.imooc.user.controller;

import com.imooc.api.controller.user.BaseControllerApi;
import com.imooc.api.controller.user.PassPortControllerApi;
import com.imooc.pojo.bo.RegisterLoginBO;
import com.imooc.enums.UserStatus;
import com.imooc.grance.result.GraceJsonResult;
import com.imooc.grance.result.ResponseStatusEnum;
import com.imooc.pojo.AppUser;
import com.imooc.user.service.UserService;
import com.imooc.utils.IPUtil;
import com.imooc.utils.JsonUtils;
import com.imooc.utils.SMSUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Map;
import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 *
 * @auther Levi
 * @Date: 2021/03/13/17:01
 * @Description:
 */
@RestController
public class PassPortController extends BaseControllerApi implements PassPortControllerApi {

    @Autowired
    private SMSUtils smsUtils;

    @Autowired
    private UserService userService;

    @Override
    public GraceJsonResult getSMSCode(@RequestParam String mobile, HttpServletRequest request) {
        //获取的用户的真实ip
        String userIp = IPUtil.getRequestIp(request);
        //生成六位随机数验证码
        String random = (int) ((Math.random() * 9 + 1) * 100000) + "";
        //设置用户每60秒只能发送一次验证码,不存在key则设置，存在则报错
        redis.setnx60s(MOBILE_SMSCODE+":"+userIp,userIp);
        //调用阿里云验证码接口发送验证码，先注释掉，验证码可以再redis可视化工具中去看
//        smsUtils.sendSMS(MyPhoneNumber.PHONE_NUM,random);
        //把验证码存入redis数据库，有效时间为5min
        redis.set(MOBILE_SMSCODE+":"+mobile,random,300);

        return GraceJsonResult.ok();
    }

    @Override
    public GraceJsonResult doLogin(@Valid @RequestBody RegisterLoginBO registerLoginBO,
                                   HttpServletRequest request, HttpServletResponse response) {
        //获取前端传过来的手机号和验证码
        String mobile = registerLoginBO.getMobile();
        String msmCode = registerLoginBO.getSmsCode();
        //获取存入redis中的验证码
        String redisMsmCode = redis.get(MOBILE_SMSCODE + ":" + mobile);
        if (StringUtils.isBlank(msmCode) || !msmCode.equalsIgnoreCase(redisMsmCode)) {
            return GraceJsonResult.errorCustom(ResponseStatusEnum.SMS_CODE_ERROR);
        }
        AppUser user = userService.queryMobileIsExist(mobile);
        //判断用户状态是否被冻结
        if (user !=null && user.getActiveStatus().equals(UserStatus.FROZEN.type)) {
            return GraceJsonResult.errorCustom(ResponseStatusEnum.USER_FROZEN);
            //用户不存在的话则创建新用户
        } else if (user == null) {
            user = userService.createUser(mobile);
        }
        //保存用户信息
        int userActiveStatus = user.getActiveStatus();
        if (userActiveStatus != UserStatus.FROZEN.type) {
            String uToken = UUID.randomUUID().toString();
            //保存用户信息到redis
            redis.set(REDIS_USER_TOKEN+":"+user.getId(),uToken);
            //登录成功之后把用户信息保存进redis，相当于之前的登录成功之后存入session中
            redis.set(REDIS_USER_INFO+":"+user.getId(), JsonUtils.objectToJson(user));
            //把uToken和uid保存到cookie中
            setCookie(request,response,"utoken",uToken,COOKIE_MONTH);
            setCookie(request,response,"uid",user.getId(),COOKIE_MONTH);
        }
        //删除redis中的验证码，验证码只能用一次，用过之后就删除掉
        redis.del(MOBILE_SMSCODE + ":" + mobile);
        //返回用户当前的状态，根据用户状态判断执行相应的操作
        return GraceJsonResult.ok(userActiveStatus);
    }

    /**
     * 用户退出登录
     * 清空redis中的token
     * 清空cookie中的utoken，uid
     *
     * @param userId
     * @param request
     * @param response
     * @return
     */
    @Override
    public GraceJsonResult logout(String userId, HttpServletRequest request, HttpServletResponse response) {
        //清楚redis中的usertoken信息
        redis.del(REDIS_USER_TOKEN+":"+userId);
        //清空cokkie中utoken和uid
        setCookie(request,response,"utoken","",COOKIE_DELETE);
        setCookie(request,response,"uid","",COOKIE_DELETE);
        return GraceJsonResult.ok();
    }


}
